import React, {memo} from 'react'
import {history, connect, useModel} from 'umi'
import {Space, Button} from 'antd'
import {CloseCircleOutlined} from '@ant-design/icons'
import {GlobalState} from '@/models/global'
import styles from './index.less'
import {RouteItem} from '@/config/routes-config'

export interface FixedBarProps {
	global: GlobalState
	dispatch: any
	user: any
}

const FixedBar = memo(
	({global: {tabRoutes}, dispatch, user}: FixedBarProps) => {
		const {initialState, setInitialState} = useModel('@@initialState')
		return (
				<div className={styles.fixedBar}>
					<Space size={12} className="menu">
						{tabRoutes.map((item: any, index: number) => (
							<Button
								type="primary"
								ghost={
									history?.location?.pathname !== item?.path
								}
								size="small"
								onClick={() => {
									setInitialState(() => ({
										...initialState,
										permission: item?.permission
											? item?.permission
											: user?.permission,
									}))
									dispatch({
										type: 'user/updatePermission',
										payload: {permission: item?.permission},
									})
									history.push({
										pathname: item?.path,
										query: item?.query,
									})
								}}>
								{item?.tabTitle ||
									item?.menuname[item.menuname.length - 1]}
								<span
									className={
										tabRoutes.length === 1
											? 'activeShow'
											: 'closeIcon'
									}>
									<CloseCircleOutlined
										onClick={(e) => {
											e.stopPropagation()
											dispatch({
												type: 'global/deleteTabs',
												payload: item,
											})

											const menu: RouteItem =
												tabRoutes[
													index === 0
														? index + 1
														: index - 1
												]
											setInitialState(() => ({
												...initialState,
												permission: menu?.permission
													? menu?.permission
													: menu?.permission,
											}))
											dispatch({
												type: 'user/updatePermission',
												payload: {
													permission:
														menu?.permission,
												},
											})
											history.push(menu?.path || '/', {})
										}}
									/>
								</span>
							</Button>
						))}
					</Space>
					<div className="closeAll">
						<Space size={12}>
							<Button
								type="primary"
								shape="round"
								ghost
								size="small"
								onClick={() => {
									dispatch({
										type: 'global/clearTabs',
									})
									history.push('/')
								}}>
								关闭
							</Button>
						</Space>
					</div>
				</div>
		)
	},
)

export default connect(({global}: any, user: any) => ({global, user}))(FixedBar)
